<!--
 * @Description: 登录
 * @Author: seadon & zhaoxiaoyang
 * @LastEditors: seadon
 * @Date: 2021-07-12 11:54:40
 * @LastEditTime: 2022-09-21 20:38:11
-->
<template>
	<div style="height: 100vh">
		<section v-if="noCheckOrg">
			<mobile-login
				v-if="mobileFlag"
				:logo-url="logoUrl"
				@insideLogin="insideLogin"
				@outsideLogin="outsideLogin"
				:hasRegister="hasRegister"
			/>
			<desktop-login
				v-else
				:logo-url="logoUrl"
				:is-show-im="isShowIm"
				:im-type="imType"
				@mode="onMode"
				@insideLogin="insideLogin"
				@outsideLogin="outsideLogin"
				:hasRegister="hasRegister"
			/>
		</section>
		<section v-else>
			<CheckOrgMobile
				:outsideOrgList="outsideOrgList"
				@enterHome="enterHome"
				v-if="mobileFlag"
			/>
			<CheckOrgDesktop
				:outsideOrgList="outsideOrgList"
				@enterHome="enterHome"
				v-else
			/>
		</section>
	</div>
</template>

<script setup lang="ts">
import { ref, unref, watch, computed } from 'vue'
import { useStore } from 'vuex'
import { message } from 'ant-design-vue'
import { getFetch, client, path, encrypt } from '@/utils'
import DesktopLogin from './Desktop.vue'
import MobileLogin from './Mobile.vue'
import CheckOrgMobile from './CheckOrgMobile.vue'
import CheckOrgDesktop from './CheckOrgDesktop.vue'
import { apiInit } from '@/services'

const store = useStore()
const api = apiInit()
const isShowIm = ref(false)
const mobileFlag = ref()
const noCheckOrg = ref(true)
const logoUrl = ref('')
const imType = ref('')
const hasRegister = computed(
	() =>
		store.state.outsideOrgRegisterListDeptList?.length &&
		store.state.outsideOrgRegisterListDeptTypeList?.length
)
const outsideOrgList = ref()
mobileFlag.value = !client.isPc()
//
// const list = {
// // 		myTask:'my_task',
// // 		myApplications:'my_approval',
// // 		launchApplication:'application_center',
// // 		personalCenter:'personal_center'
// // 	}
// // let tabs = computed(()=>store.state.tenant.mobile_tab_list)
const GetQueryString = (param: any): string => {
	const currentUrl = window.location.href
	let arr = currentUrl.split('?')
	if (arr.length > 1) {
		arr = arr[1].split('&')
		for (let i = 0; i < arr.length; i++) {
			const item = arr[i].split('=')
			if (item[0] == param) {
				return item[1]
			}
		}
		return ''
	} else {
		return ''
	}
}
//清空cookie

const insideLogin = async (
	params: any,
	type: string,
	language: '',
	callback?: Function
): Promise<void> => {
	const baseInfo: any = process.env.VUE_APP_BASE_INFO_PATH
	const http = getFetch(baseInfo)
	const redirectUrl: any = GetQueryString('redirect_uri')
	const pwdAuth: any = process.env.VUE_APP_PWD_AUTH_PATH
	const pwd = encrypt(params.password)
	const result = await http.post(pwdAuth, {
		...params,
		user_id: params.account.trim(),
		account: params.account.trim(),
		password: pwd,
		type: 'rsa',
		language,
	})
	if (result.data) {
		let url
		if (type === 'pc') {
			url = path.getFullPath('/')
			window.location.replace(
				redirectUrl ? decodeURIComponent(redirectUrl) : url
			)
		} else {
			url = path.getFullPath('/')
			window.location.href = redirectUrl ? decodeURIComponent(redirectUrl) : url
		}
	} else {
		message.error(result.msg || result.message)
		if (typeof callback === 'function') {
			callback()
		}
	}
}
const outsideLogin = async (
	userId: string,
	password: string,
	language: string
) => {
	let params: any = {
		captcha: '',
		captcha_id: '',
		language,
		password: encrypt(password),
		type: 'rsa',
		user_id: userId,
	}
	let result = await api.baseAuto.LoginExternalMulPwdPublicV1POST({
		payload: params,
	})
	if (result.code === '000000') {
		let { data, code, msg } =
			await api.baseAuto.ListExternalMulDeptPrivateV1POST({})
		if (code === '000000') {
			if (data?.length === 1) {
				let { code, msg } =
					await api.baseAuto.SwitchDeptExternalEmployeePrivateV1POST({
						query: {
							employeeId: data[0].employee_id,
						},
					})
				enterHome(
					code as string,
					msg as string,
					data[0],
					mobileFlag ? 'mobile' : 'pc'
				)
			} else {
				outsideOrgList.value = data
				noCheckOrg.value = false
			}
		} else {
			message.error(msg!)
		}
	} else {
		message.error(result.msg! || result.message!)
	}
}
const enterHome = (code: string, msg: string, detail: any, type: string) => {
	const redirectUrl: any = GetQueryString('redirect_uri')
	if (code === '000000') {
		let url
		if (type === 'pc') {
			url = path.getFullPath(
				detail.redirect_to_custom_url_after_login === '1'
					? detail.pc_redirect_url_after_login
					: '/'
			)

			window.location.href =
				redirectUrl && detail.redirect_to_custom_url_after_login === '0'
					? decodeURIComponent(redirectUrl)
					: url
		} else {
			url = path.getFullPath(
				detail.redirect_to_custom_url_after_login === '1'
					? detail.mb_redirect_url_after_login
					: '/'
			)

			window.location.href =
				redirectUrl && detail.redirect_to_custom_url_after_login === '0'
					? decodeURIComponent(redirectUrl)
					: url
		}
	} else {
		message.error(msg)
	}
}
const onMode = (type: string) => {
	const authPath = process.env.VUE_APP_AUTH_PATH
	const redirectUrl: any = GetQueryString('redirect_uri')
	const url = `${authPath}?redirectUri=${redirectUrl}&fixedLoginType=${type}`
	window.location.replace(url)
}
const tenantDetail = ref()
const init = async () => {
	if (GetQueryString('login_status') === 'external_org_login') {
		let { data, code, msg } =
			await api.baseAuto.ListExternalMulDeptPrivateV1POST({})
		if (code === '000000') {
			outsideOrgList.value = data
			noCheckOrg.value = false
		} else {
			message.error(msg!)
		}
	}
	logoUrl.value = tenantDetail.value?.icon_url
	const loginTypes: any = tenantDetail.value?.login_types.split(',')
	const removeZeroType: any = loginTypes.filter((item: any) => {
		return item !== '0'
	})
	isShowIm.value = removeZeroType.length
	imType.value = removeZeroType[0]
	if (!loginTypes.includes('0')) {
		onMode(unref(imType))
		return false
	}
	const parent: any = window.parent
	if (window.parent) {
		parent.postMessage({
			isLogin: true,
		})
	}
}
watch(
	() => store.state.tenant,
	value => {
		tenantDetail.value = value
		init()
	},
	{
		deep: true,
		immediate: true,
	}
)
</script>
<style lang="less">
section {
	width: 100%;
	height: 100%;
}
</style>
